<template>
  <div class="friend">
    firend
    <input
      type="text"
      v-model="value"
      v-enterNumber
    >
    <br>
    <button v-ripple></button>
    <van-uploader
      :after-read="afterRead"
      :max-size="3000 * 1024"
      @oversize="onOversize"
    />
    <br>
    <span>这是个动画效果</span>
  </div>
</template>

<script>
export default {
  name: 'friend',
  data () {
    return {
      value: ''
    }
  },
  methods: {
    afterRead (file) {
      this.dealImg(file)
    },
    onOversize (file) {
      this.$toast('文件大小不能超过 3m ！');
    },
    dealImg (file) {
      const w = 1920
      let quality = 0.7
      let newImage = new Image();
      newImage.src = file.content;
      let imgWidth, imgHeight;
      return new Promise((resolve, reject) => {
        newImage.onload = function () {
          imgWidth = this.width;
          imgHeight = this.height;
          let canvas = document.createElement("canvas");
          let ctx = canvas.getContext("2d");
          if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
              canvas.width = w;
              canvas.height = w * imgHeight / imgWidth;
            } else {
              canvas.height = w;
              canvas.width = w * imgWidth / imgHeight;
            }
          } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 0.7;
          }

          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
          let base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句

          // 如想确保图片压缩到自己想要的尺寸,如要求在300kb，请加以下语句，quality初始值根据情况自定
          while (base64.length / 1024 > 300) {
            quality -= 0.01;
            base64 = canvas.toDataURL("image/jpeg", quality);
          }
          resolve(base64)
        }
      })
    }
  }
}
</script>

<style scoped>
.friend {
  height: 100%;
}

button {
  margin-top: 15px;
  width: 150px;
  height: 50px;
  border-radius: 5px;
  background: #fff;
  position: relative;
}
span {
  position: relative;
}
span::after {
  content: '';
  height: 2px;
  width: 0;
  position: absolute;
  bottom: -5px;
  left: 0;
  background-color: pink;
  transition: width 0.5s;
}
span:hover::after {
  width: 100%;
}
</style>